package com.lmh.utils;

import com.lmh.entity.User;
import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;

public class Maps {

    private Map<String, Object> paramMap = new HashMap<>();

    private Maps() {

    }

    private Maps(String key, Object value) {
        paramMap.put(key, value);
    }

    private Maps(Integer id) {
        paramMap.put("id", id);
    }

    public static Maps build() {
        return new Maps();
    }

    public static Maps build(String key, Object value) {
        return new Maps(key, value);
    }

    public static Maps build(Integer id) {
        return new Maps(id);
    }

    public Maps put(String key, Object value) {
        paramMap.put(key, value);
        return this;
    }

    public Maps putId(Integer id) {
        paramMap.put("id", id);
        return this;
    }

    public Maps add(String key, Object value) {
        paramMap.put(key, value);
        return this;
    }

    public Maps add(Map<String, Object> map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            paramMap.put(entry.getKey(), entry.getValue());
        }
        return this;
    }

    public Map<String, Object> getParamMap() {
        return paramMap;
    }

    // 对象转Map，用于更新
    public <T> Map<String, Object> beanToMapForUpdate(T bean) {
        if(bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                paramMap.put("update"+upperFirstLetter(key+""), beanMap.get(key));
            }
        }
        return paramMap;
    }

    // 对象转Map，用于查询
    public <T> Map<String, Object> beanToMap(T bean) {
        if(bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                paramMap.put(key+"", beanMap.get(key));
            }
        }
        return paramMap;
    }

    public static String upperFirstLetter(String str) {
        char[] chars = str.toCharArray();
        if (chars[0]>='a' && chars[0]<='z') {
            chars[0] = (char) (chars[0] - 32);
        }
        return new String(chars);
    }

    public static void main(String[] args) {
        System.out.println(Maps.build().beanToMap(new User()));
    }
}
